import { apiClient, type LoginRequest, type LoginResponse } from './api'

// 本地存储键名
const STORAGE_KEYS = {
  TOKEN: 'auth_token',
  USER_INFO: 'user_info',
  REMEMBER_ME: 'remember_me'
}

// 用户信息类型
export type UserInfo = LoginResponse['userInfo']

// 认证服务类
export class AuthService {
  // 登录
  async login(credentials: LoginRequest, rememberMe: boolean = false): Promise<UserInfo> {
    try {
      const response = await apiClient.login(credentials)
      
      if (response.code === 200 && response.data) {
        // 保存token和用户信息
        this.setToken(response.data.token)
        this.setUserInfo(response.data.userInfo)
        
        // 保存记住我状态
        if (rememberMe) {
          localStorage.setItem(STORAGE_KEYS.REMEMBER_ME, 'true')
        } else {
          localStorage.removeItem(STORAGE_KEYS.REMEMBER_ME)
        }
        
        return response.data.userInfo
      } else {
        throw new Error(response.msg || '登录失败')
      }
    } catch (error) {
      console.error('Login error:', error)
      throw error
    }
  }

  // 登出
  async logout(): Promise<void> {
    try {
      // 调用服务端登出接口
      await apiClient.logout()
    } catch (error) {
      console.error('Logout API error:', error)
      // 即使服务端登出失败，也要清除本地数据
    } finally {
      // 清除本地存储
      this.clearAuth()
    }
  }

  // 获取当前用户信息
  getUserInfo(): UserInfo | null {
    const userInfoStr = localStorage.getItem(STORAGE_KEYS.USER_INFO)
    if (userInfoStr) {
      try {
        return JSON.parse(userInfoStr)
      } catch (error) {
        console.error('Failed to parse user info:', error)
        return null
      }
    }
    return null
  }

  // 设置用户信息
  setUserInfo(userInfo: UserInfo): void {
    localStorage.setItem(STORAGE_KEYS.USER_INFO, JSON.stringify(userInfo))
  }

  // 获取token
  getToken(): string | null {
    return localStorage.getItem(STORAGE_KEYS.TOKEN)
  }

  // 设置token
  setToken(token: string): void {
    localStorage.setItem(STORAGE_KEYS.TOKEN, token)
  }

  // 检查是否已登录
  isAuthenticated(): boolean {
    const token = this.getToken()
    const userInfo = this.getUserInfo()
    return !!(token && userInfo)
  }

  // 检查token是否有效（简单的JWT过期检查）
  isTokenValid(): boolean {
    const token = this.getToken()
    if (!token) return false

    try {
      // 简单的JWT解析（仅解析payload部分）
      const tokenParts = token.replace('Bearer ', '').split('.')
      if (tokenParts.length !== 3) return false

      const payload = JSON.parse(atob(tokenParts[1]))
      const currentTime = Math.floor(Date.now() / 1000)
      
      // 检查是否过期
      return payload.exp > currentTime
    } catch (error) {
      console.error('Token validation error:', error)
      return false
    }
  }

  // 清除认证信息
  clearAuth(): void {
    localStorage.removeItem(STORAGE_KEYS.TOKEN)
    localStorage.removeItem(STORAGE_KEYS.USER_INFO)
    localStorage.removeItem(STORAGE_KEYS.REMEMBER_ME)
  }

  // 检查是否记住密码
  isRememberMe(): boolean {
    return localStorage.getItem(STORAGE_KEYS.REMEMBER_ME) === 'true'
  }

  // 刷新用户信息
  async refreshUserInfo(): Promise<UserInfo | null> {
    try {
      const response = await apiClient.getUserInfo()
      if (response.code === 200 && response.data) {
        this.setUserInfo(response.data)
        return response.data
      }
      return null
    } catch (error) {
      console.error('Failed to refresh user info:', error)
      return null
    }
  }
}

// 导出默认认证服务实例
export const authService = new AuthService()
